<?php
namespace app\index\controller\dictionary;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据

/*
* 前台-字典维护 -> 组合项目
* index/dictionary.zhuhe/index
*/
class Zhuhe extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['info','del','find_xmlist']; //无需鉴权的方法，但需要登录

    //初始化
    public function initialize()
    {
        parent::initialize();
    }

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $post = $this->request->only(['dicttype','keyword','status','page'],'post');
                if(!isset($post['dicttype']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                $post['dicttype'] = strtolower($post['dicttype']);
                //获取列表
                //条件
                $map = [
                    ['clinic_id','=', $this->admin['clinic_id']],
                    ['type','=','0'], //大类型0=组合项目,1=疗程
                ];
                $page = isset($post['page']) ? $post['page'] : 1;
                if(isset($post['dicttype']) && $post['dicttype'] != '')
                {
                    if(strtoupper($post['dicttype']) != 'ALL')
                    {
                        $map[] = ['zh_type','=',$post['dicttype']];
                    }
                }
                if(isset($post['keyword']) && $post['keyword'] != '')
                {
                    $map[] = ['name|bianma|py_code|wb_code','like','%' . $post['keyword'] . '%'];
                }
                if(isset($post['status']) && $post['status'] != '')
                {
                    if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
                }
                $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhuhe')->where($map)->field('*')
                        ->order('create_time desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
                }
                $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
                $lsUnitArr = ClinicDict::getZheheXiangMuUnitList();
                $addressArr = ClinicDict::getJianYanDiDianList();
                foreach ($res['data'] as $key => &$val) {
                    $val['ls_unit_txt'] = _getDictNameTxt($val['ls_unit'],$lsUnitArr);
                    $val['address_txt'] = _getDictNameTxt($val['address'],$addressArr);
                    $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d Hi:s') : '';
                }
                return json($res);
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
		$this->assign([
            'zhxm_cate_list' => ClinicDict::getZhuHeXmCateList(), //组合项目分类列表
        ]);
        return $this->view->fetch();
    }
    //修改 + 新增
    public function info($id = 0)
    {
        if($this->request->isAjax())
        {
            try
            {
                $data = $this->request->only([
                    'id','bianma','name','zh_type','ls_unit','address','biaoben',
                    'py_code','wb_code','zh_price','remarks','price','xm_tc_mode',
                    'xm_tc_val','status','table_list',
                ],'post');
                if(!isset($data['id']))
                {
                    return json(['err' => '1', 'msg' => '参数错误，无法执行']);
                }
                if(!isset($data['name']) || $data['name'] == '')
                {
                    return json(['err' => '2', 'msg' => '必须输入一个名称']);
                }
                if(!isset($data['price']) || $data['price'] == '')
                {
                    return json(['err' => '3', 'msg' => '请输入单价']);
                }
                if(!isset($data['table_list']) || count($data['table_list']) <= 0)
                {
                    return json(['err' => '4', 'msg' => '组合中未添加子项目']);
                }
                $data['ext_json'] = json_encode($data['table_list'],JSON_UNESCAPED_UNICODE);
                $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhuhe')
                        ->where(['id' => intval($data['id']), 'type' => '0', 'clinic_id' => $this->admin['clinic_id']])->find();
                if($info) //数据已存在
                {
                    unset($data['table_list'],$data['id']);
                    $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhuhe')->where(['id' => $info['id']])->update($data);
                }else{ //数据不存在
                    unset($data['table_list'],$data['id']);
                    $sqlData = array_merge($data,[
                        'type' => '0', //大类型0=组合项目,1=疗程
                        'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                        'create_time' => time(), //创建时间
                    ]);
                    $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhuhe')->insertGetId($sqlData);
                }
                unset($data,$info,$sqlData);
                if(!$editRes) return json(['err' => '2', 'msg' => '组合项目数据保存失败']);
                return json(['err' => '0', 'msg' => '组合项目数据已保存成功']);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }else{
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhuhe')
                    ->where(['id' => intval($id), 'type' => '0', 'clinic_id' => $this->admin['clinic_id']])->find();
            $tableList = !$info['ext_json'] ? [] : json_decode($info['ext_json'],true);
            $jcbweiArr = ClinicDictsheet::getDictList('jcbwei',$this->admin['clinic_id'],'id,name'); //检查部位
            $this->assign([
                'info' => $info,
                'table_list' => $tableList, //子项目列表
                'buwei_list' => $jcbweiArr, //检查部位
                'new_bianhao' => $this->get_newbianma(), //生成一个新的组合项目编号
                'zhxm_cate_list' => ClinicDict::getZhuHeXmCateList(), //组合项目分类列表
                'zhxm_unit_list' => ClinicDict::getZheheXiangMuUnitList(), //组合项目单位
                'zhxm_address_list' => ClinicDict::getJianYanDiDianList(), //检验地点分类
                'zhxm_beioben_list' => ClinicDict::getBiaoBenCateList(), //标本列表分类
            ]);
            return $this->view->fetch();
        }
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $r = false;
            $map = [
                ['id','in',$data['id']],
                ['clinic_id','=',$this->admin['clinic_id']],
                ['type','=','0'], //大类型0=组合项目,1=疗程
            ];
            //字典表数据_通用
            $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhuhe')->where($map)->delete();
            if(!$r) return json(['err' => '2', 'msg' => '删除失败，请重试']);
            return json(['err' => '0', 'msg' => '删除成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //搜索添加组合项目 下的子项目
    public function find_xmlist($type = 'zhenliao')
    {
        $type = strtolower($type);
        if(!$this->request->isAjax() || !$type)
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['keyword','limit','page'],'post');
            if(!isset($data['page']))
            {
                return json(['err' => '2', 'msg' => '参数错误，无法获取数据']);
            }
            //条件
            $map = [['clinic_id','=', $this->admin['clinic_id']],['status','=','1']];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['name|bianma|py_code|wb_code','like','%' . $data['keyword'] . '%'];
            }
            $limit = intval($data['limit']) > 0 ? intval($data['limit']) : 20;
            $field = 'id,name,bianma,price,ls_unit';
            if($type == 'zhenliao')
            {
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_zhenliao')->where($map)->field($field)
                        ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['err' => '3', 'msg' => '当前页下无数据']);
                }
                $res = ['err' => '0', 'page' => $data['page'], 'limit' => $limit, 'data' => $list->items()];
                $lsUnitArr = ClinicDictsheet::getDictList('zlxmunit',$this->admin['clinic_id'],'id,name');
                foreach ($res['data'] as $key => &$val) {
                    $val['type'] = $type;
                    $val['type_txt'] = '诊疗项目';
                    $val['ls_unit_txt'] = _getDictNameTxt($val['ls_unit'],$lsUnitArr);
                }
            }
            if($type == 'cailiao')
            {
                $map[] = ['drugs_type', '=', '2'];
                $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field($field)
                        ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
                if (count($list) <= 0) {
                    return json(['err' => '4', 'msg' => '当前页下无数据']);
                }
                $res = ['err' => '0', 'page' => $data['page'], 'limit' => $limit, 'data' => $list->items()];
                $lsUnitArr = ClinicDict::getZhongYaoUnitList();
                foreach ($res['data'] as $key => &$val) {
                    $val['type'] = $type;
                    $val['type_txt'] = '材料项目';
                    $val['ls_unit_txt'] = _getDictNameTxt($val['ls_unit'],$lsUnitArr);
                }
            }
            return json($res);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //生成一个新的组合项目编号
    private function get_newbianma()
    {
        //['type','=','0'], //大类型0=组合项目,1=疗程
        $newBianMa = date('Ym') . rand(10000,99999);
        return $newBianMa;
    }
}
